<template>
  <div class="container">
      <a-page-header
       class="header"
        title="ids抓包过滤规则管理"
        sub-title="配置ids抓包过滤规则"
    />
     <a-divider></a-divider>
     <a-button type="primary" @click="addRecord"> 新增</a-button>
     <div style="dispaly:block;height:20px;width:100%"></div>
    <a-table :columns="columns" :data-source="data" bordered>
    <template
      v-for="col in ['name', 'cont']"
      :slot="col"
      slot-scope="text, record"
    >
      <div :key="col">
        <a-input
          v-if="record.editable"
          style="margin: -5px 0"
          :value="text"
          @change="e => handleChange(e.target.value, record.key, col)"
        />
        <template v-else>
          {{ text }}
        </template>
      </div>
    </template>
    <template slot="operation" slot-scope="text, record">
      <div class="editable-row-operations">
        <span v-if="record.editable">
          <a @click="() => save(record.key)">Save</a>
          <a-popconfirm title="Sure to cancel?" @confirm="() => cancel(record.key)">
            <a>Cancel</a>
          </a-popconfirm>
        </span>
        <span v-else>
          <a :disabled="editingKey !== ''" @click="() => edit(record.key)">Edit</a>
        </span>
        <span> <a-button type="link" @click="deleteFilterRule(record.id)"> 删除</a-button> </span>
      </div>
    </template>
  </a-table>
    <a-modal
        title="添加入侵日志接收者"
        :visible="visible"
        :confirm-loading="confirmLoading"
        @ok="handleOk"
        @cancel="handleCancel"
      >
         <a-form :form="recordModal" @submit="handleSubmit">
            <a-form-item v-bind="formItemLayout" label="规则名">
              <a-input
                v-decorator="[
                  'name',
                  {
                    rules: [
                      {
                        required: true,
                        message: '输入名称',
                      },
                    ],
                  },
                ]"
              />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="过滤规则">
              <a-textarea
                v-decorator="[
                  'cont',
                  {
                    rules: [
                      {
                        required: true,
                        message: '输入规则表达式',
                      },
                    ],
                  },
                ]"
              />
            </a-form-item>
        </a-form>
      </a-modal>


  </div>
</template>
<script >
import ContentCard from "@/components/content-card.vue"
import {filterRuleUpdate, filterRuleDelete, filterRuleAdd, fileRuleList} from "@/api/filter_rule/filter_rule"

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    width: '15%',
    scopedSlots: { customRender: 'age' },
  },
  {
    title: '过滤规则名',
    dataIndex: 'name',
    width: '25%',
    scopedSlots: { customRender: 'name' },
  },
  {
  title: '过滤规则表达式（仅支持libcap语法）',
  dataIndex: 'cont',
  width: '40%',
  scopedSlots: { customRender: 'name' },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: '10%',
    scopedSlots: { customRender: 'operation' },
  },
];

export default {
  data() {
    return {
      data:[],
      cacheData:[],
      columns,
      editingKey: '',

      visible: false,
      confirmLoading: false,
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
      },
    };
  },
  methods: {
    handleChange(value, key, column) {
      const newData = [...this.data];
      const target = newData.find(item => key === item.key);
      if (target) {
        target[column] = value;
        this.data = newData;
      }
    },
    edit(key) {
      const newData = [...this.data];
      const target = newData.find(item => key === item.key);
      this.editingKey = key;
      if (target) {
        target.editable = true;
        this.data = newData;
      }
    },
    save(key) {
      const newData = [...this.data];
      const newCacheData = [...this.cacheData];
      const target = newData.find(item => key === item.key);
      const targetCache = newCacheData.find(item => key === item.key);
      if (target && targetCache) {
        delete target.editable;
        this.data = newData;
        Object.assign(targetCache, target);
        this.cacheData = newCacheData;
      }
      this.editingKey = '';
      console.log("new Date: ", target)
      filterRuleUpdate(target)
      .then(data=>{
        console.log(data)
        this.$message.success("数据更新成功")
      })
      .catch(err=>{
        this.$message.error("数据更新出错")
      })
    },
    cancel(key) {
      const newData = [...this.data];
      const target = newData.find(item => key === item.key);
      this.editingKey = '';
      if (target) {
        Object.assign(target, this.cacheData.find(item => key === item.key));
        delete target.editable;
        this.data = newData;
      }
    },
    addRecord(){
      this.visible = true;
    },
    updateFileRuleList(){
      var param = {}
      fileRuleList(param)
      .then(data=>{
        this.data = data.data;
        this.cacheData = this.data.map(item => ({ ...item }));
      })
      .catch(err=>{
        this.$message.error("获取数据失败")
      })
    },
    deleteFilterRule(id){
      var param = {"id": id}
      filterRuleDelete(param)
      .then(data=>{
        this.$message.success("删除完成")
        this.updateFileRuleList()
      })
      .catch(err=>{
        this.$message.error("删除出错")
      })
    },
    showModel(){
      this.visible = true;
    },
    handleOk(e){
        this.recordModal.validateFieldsAndScroll((err, values) => {
          if (!err) {
            console.log('Received values of form: ', values);
            filterRuleAdd(values)
            .then(data=>{
              this.$message.success("添加完成")
              this.updateFileRuleList()
            })
            .catch(err=>{
              this.$message.error("添加错误")
            })
            this.confirmLoading = false;
            this.visible = false;
          }
        });
        console.log("ok")
    },
    handleCancel(){
      this.visible = false
    },
    handleSubmit(){

    }
  },
  created(){
    this.updateFileRuleList();
  },
  beforeCreate(){
      this.recordModal = this.$form.createForm(this, { name: 'recordModal' });
  }
};
</script>

<style lang="less" scoped>
.container{
  height: 100%;
  width: 100%;
  padding-left: 5%;
  padding-right: 5%;
  // background-color:grey;
}

.title-text{
  font-size: 18px;
  font-weight: bold;
}

.header{
  margin-left: -30px;
}

.detail-panel{
  background-color: antiquewhite;
  margin-bottom: 20px;
}

.grid-content{
  display: flex;
  justify-content: center;
}
</style>
